import { addJobsDataApi, deleteJobsDataApi, getJobsApi, updateJobsDataApi } from "@/api/job";
import { App, Button, Checkbox, Form, Input, Modal, Space, Table, type TableProps } from "antd"
import { useEffect, useMemo, useState } from "react";
import { ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons';
import type { SearchProps } from "antd/es/input";
import TextArea from "antd/es/input/TextArea";
import MyCard from "@/components/card";
interface DataType {
  _id: string;
  name: string;
  desc: string;
}

const fixedColumns: TableProps<DataType>['columns'] = [

  {
    title: '职务名称',
    dataIndex: 'name',
  },
  {
    title: '职位描述',
    dataIndex: 'desc'
  },

];







const JobManage = () => {
  const [searchData, setSearchData] = useState({ searchValue: '' });
  const [open, setOpen] = useState(false);
  const [data, setData] = useState<{ rows: DataType[], total: number }>({ rows: [], total: 0 });
  const [oldData, setOldData] = useState<DataType>({ _id: '', name: '', desc: '' });
  const [form] = Form.useForm();
  const { message, modal } = App.useApp();
  const [pageData, setPageData] = useState({ currentPage: 1, pageSize: 10 })
  useEffect(() => {
    getJobs();
  }, [searchData, pageData]);

  useEffect(() => {
    if (!open) {
      setOldData({ _id: '', name: '', desc: '' });
      form.resetFields();
    }
  }, [open])

  //类似计算属性
  const modalTitle = useMemo(() => {
    return oldData._id ? '编辑职务' : '新增职务'
  }, [oldData]);
  // const checkboxData = data.map(item => item._id)
  // const checkAll = checkboxData.length === checkedList.length;
  // const onCheckAllChange: CheckboxProps['onChange'] = (e) => {
  //   setCheckedList(e.target.checked ? checkboxData : []);
  // };

  //表单额外列配置
  const columns: TableProps<DataType>['columns'] = [
    {
      title: () => (
        <Checkbox ></Checkbox>
      ),
      render: () => (
        <Checkbox ></Checkbox>
      )
    },
    ...fixedColumns, {
      title: '操作',
      key: 'action',
      render: (item) => (
        <Space size="middle">
          <a onClick={() => { onUpdate(item) }}>编辑</a>
          <a onClick={() => { showConfirm(item._id) }}>删除</a>
        </Space>
      ),
    },

  ];



  //搜索框
  const onSearch: SearchProps['onSearch'] = (value) => {
    setSearchData({ searchValue: value })
  };

  //点击修改保存数据、打开弹窗、数据回显
  const onUpdate = (item: any) => {
    setOldData(item);
    setOpen(true);
    form.setFieldsValue(item);
  }

  //删除按钮
  const showConfirm = (_id: string) => {
    modal.confirm({
      title: '删除确认',
      icon: <ExclamationCircleFilled />,
      content: '职务删除后无法恢复，确定要删除吗？',
      onOk() {
        onDelete(_id);
        getJobs();
      },
      onCancel() {
      },
    });
  };



  //弹窗确认 新增/修改数据
  const onOK = () => {
    if (oldData._id) {
      updateJobsDataApi({
        ...oldData,
        ...form.getFieldsValue()
      }).then(res => {
        if (res.code == 200) {
          message.success('修改成功！')
          setOpen(false);
          getJobs();
        } else {
          message.error(res.message)
        }
      })
      setOldData({ _id: '', name: '', desc: '' });
    } else {

      addJobsDataApi(form.getFieldsValue()).then(res => {
        if (res.code == 200) {
          message.success('新增成功！')
          setOpen(false);
          getJobs();
        } else {
          message.error(res.message)
        }
      })
    }
  }
  //弹窗关闭
  const onCancel = () => {
    setOpen(false);
  }

  //获取数据
  const getJobs = () => {
    getJobsApi({
      ...searchData,
      ...pageData
    }).then(res => {
      if (res.code == 200) {
        setData(res.data);
      }
    })
  }



  //删除
  const onDelete = (_id: string) => {
    deleteJobsDataApi({ _id }).then(res => {
      if (res.code == 200) {
        message.success('删除成功！')
        getJobs();
      } else {
        message.error(res.message)
      }
    })
  }
  //分页
  const changePageData = (currentPage: number, pageSize: number) => {
    setPageData({ currentPage, pageSize })
  }
  return (
    <>
      <MyCard title='职务管理'>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
          <Input.Search placeholder="请输入关键字" style={{ width: 300 }} allowClear onSearch={onSearch} />
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setOpen(true)}>新增职务</Button>
            <Button color="primary" variant="outlined">批量删除</Button>
          </Space>
        </div>

        <Table<DataType> columns={columns} dataSource={data.rows} rowKey="_id" pagination={{
          total: data.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `总计 ${total} 条数据`,
          pageSizeOptions: [5, 10, 20, 50],
          onChange: changePageData
        }} />
      </MyCard>



      <Modal
        title={modalTitle}
        // closable={{ 'aria-label': 'Custom Close Button' }}
        open={open}
        onOk={onOK}
        onCancel={onCancel}
        forceRender={true}
      >
        <Form
          form={form}
          name="jobForm"
          labelCol={{ style: { width: 80 } }}
          style={{ marginBottom: 20 }}
        >
          <Form.Item name="name" label="职务名称" rules={[{ required: true, message: '职务名称不能为空' }]}>
            <Input></Input>
          </Form.Item>
          <Form.Item name="desc" label="职务描述" >
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>



    </>
  )
}

export default JobManage